# -*- coding: utf-8 -*-
#https://github.com/AGNORT/Face-datasets
import os
from PIL import Image
import shutil

# 原始目录
src_dir = "./orl_faces"
# 目标目录
train_dir = "./orl_faces_processed/train"
test_dir = "./orl_faces_processed/test"

# 创建目标目录
os.makedirs(train_dir, exist_ok=True)
os.makedirs(test_dir, exist_ok=True)

# 遍历 s1~s40 文件夹
for folder_name in sorted(os.listdir(src_dir)):
    folder_path = os.path.join(src_dir, folder_name)
    if not os.path.isdir(folder_path):
        continue

    # 遍历每个文件夹下的图片
    for file_name in sorted(os.listdir(folder_path), key=lambda x: int(os.path.splitext(x)[0])):
        if file_name.endswith(".pgm"):
            pgm_path = os.path.join(folder_path, file_name)
            img = Image.open(pgm_path).convert("RGB")  # 转为RGB

            # 新的文件名
            new_file_name = f"{folder_name}_{os.path.splitext(file_name)[0]}.jpg"

            if int(os.path.splitext(file_name)[0]) == 1:
                dst_path = os.path.join(test_dir, new_file_name)
            else:
                dst_path = os.path.join(train_dir, new_file_name)

            # 保存为 .jpg
            img.save(dst_path, "JPEG")

print("转换并移动完成！")
